<template>
  <div class="data-table-container layout-padding">
    <el-card class="layout-padding-auto" shadow="hover">
      <el-form ref="queryFormRef" :model="state.tableData.param.params" inline>
        <el-form-item class="!mr-4" prop="businessType" style="width: 11%">
          <el-select v-model="state.tableData.param.params.businessType"
                     clearable
                     placeholder="请选择操作类型"
                     size="default">
            <el-option
                v-for="item in state.operTypeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="!mr-4" prop="status" style="width: 11%">
          <el-select v-model="state.tableData.param.params.status"
                     clearable
                     placeholder="请选择操作状态"
                     size="default">
            <el-option
                v-for="item in state.commonStatusList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-auth="'user.list'" class="!mr-4">
          <el-button size="default" type="primary" @click="getTableData">
            <el-icon>
              <ele-Search/>
            </el-icon>
            查询
          </el-button>
        </el-form-item>
        <el-form-item v-auth="'user.list'" class="!mr-4">
          <el-button size="default" type="primary" @click="onHandleResetFields">
            <el-icon>
              <ele-Refresh/>
            </el-icon>
            重置
          </el-button>
        </el-form-item>
        <el-form-item v-auth="'user.list'" class="!mr-4">
          <el-button size="default" type="success" @click="cleanAll">
            <el-icon>
              <ele-DeleteFilled/>
            </el-icon>
            清空全部
          </el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="state.tableData.loading" :data="state.tableData.data" highlight-current-row
                style="width: 100%"
                @sort-change="handleSortChange">
        <el-table-column align="center" label="日志编号" prop="id"/>
        <el-table-column :show-overflow-tooltip="true" align="center" label="系统模块" prop="title"/>
        <el-table-column align="center" label="操作类型" prop="businessType">
          <template v-slot="scope">
            <dict-tag :options="sys_oper_type" :value="scope.row.businessType"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作人员" prop="operName" show-overflow-tooltip width="110"/>
        <el-table-column align="center" label="操作地址" prop="operIp" show-overflow-tooltip width="130"/>
        <el-table-column align="center" label="操作地点" prop="operLocation" show-overflow-tooltip/>
        <el-table-column align="center" label="操作状态" prop="status">
          <template v-slot="scope">
            <dict-tag :options="sys_common_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作日期" prop="operTime"
                         show-overflow-tooltip
                         sortable/>
        <el-table-column :show-overflow-tooltip="true" align="center"
                         label="消耗时间" prop="costTime"
                         sortable width="120">
          <template v-slot="scope">
            <span>{{ scope.row.costTime }}毫秒</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button :disabled="scope.row.loginName === 'admin'" size="small" text
                       type="primary" @click="onOpenEditUser('view', scope.row)">
              详细
            </el-button>
            <el-button :disabled="scope.row.loginName === 'admin'" size="small" text
                       type="danger" @click="onRowDel(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="state.tableData.param.pageNum"
                     v-model:page-size="state.tableData.param.pageSize" :page-sizes="[10, 20, 30]" :pager-count="5"
                     :total="state.tableData.total" background class="mt15"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange">
      </el-pagination>
    </el-card>
    <serverDialog ref="serverDialogRef" @refresh="getTableData()"/>
  </div>
</template>

<script lang="ts" name="systemUser" setup>
import {defineAsyncComponent, getCurrentInstance, onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {logApi} from "/@/api/sys/log";
import {dictDataApi} from "/@/api/sys/dictData";

// 引入组件
const serverDialog = defineAsyncComponent(() => import('/@/views/system/log/dialog.vue'));

const {proxy} = getCurrentInstance();
const {sys_oper_type, sys_common_status} = proxy.useDict("sys_oper_type", "sys_common_status");


// 定义变量内容
const serverDialogRef = ref();
const queryFormRef = ref();
const state = reactive<SysUserState>({
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 10,
      params: {
        businessType: '',
        status: '',
      },
    },
  },
  operTypeList: [],
  commonStatusList: []
});


const handleSortChange = (data: any) => {
  if (data.order) {
    if (data.order.indexOf('asc') > -1) {
      state.tableData.param.sortOrder = 'asc'
    } else {
      state.tableData.param.sortOrder = 'desc'
    }
    state.tableData.param.sortName = data.prop
  }
  getTableData();
};

// 初始化表格数据
const getTableData = () => {
  state.tableData.loading = true;
  logApi()
      .getTableData(state.tableData.param)
      .then((res: any) => {
        state.tableData.data = res.data.records;
        state.tableData.total = res.data.total;
        state.tableData.loading = false;
      })
      .catch(() => {
        state.tableData.loading = false;
      });
};

const cleanAll = () => {
  logApi()
      .delAllRecord()
      .then(res => {
        ElMessage.success(res.msg || '清空成功')
        getTableData()
      })
};

// 打开修改用户弹窗
const onOpenEditUser = (type: string, row: RowUserType) => {
  serverDialogRef.value.openDialog(type, row);
};
// 删除用户
const onRowDel = (row: RowUserType) => {
  ElMessageBox.confirm(`此操作将永久删除账户“${row.userName}”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    logApi()
        .delRecord(row)
        .then(() => {
          getTableData();
          ElMessage.success('删除成功');
        });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};
// 分页改变
const onHandleSizeChange = (val: number) => {
  state.tableData.param.pageSize = val;
  getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.tableData.param.pageNum = val;
  getTableData();
};
// 页面加载时
onMounted(() => {
  getTableData();

  // 操作类型
  dictDataApi()
      .getDictByType("sys_oper_type")
      .then(res => {
        state.operTypeList = res.data;
      })

  // 操作状态
  dictDataApi()
      .getDictByType("sys_common_status")
      .then(res => {
        state.commonStatusList = res.data;
      })

});
// 重置查询表单
const onHandleResetFields = () => {
  queryFormRef.value.resetFields();
  getTableData();
};
</script>
